/**
* AutoSWF - Cody Cushing. March 26, 2009
* Copyright (c) 2009 Cody Cushing
* No use restrictions. Maintain this notice in all versions. 
**/

package com.autoswf.taskrunner.loadtasks
{
	import com.autoswf.taskrunner.ITask;
	import com.autoswf.taskrunner.TaskEvent;
	
	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.net.URLRequest;
	import flash.system.ApplicationDomain;
	import flash.system.LoaderContext;
	
	
	/**
	 * Intended for loading modules, use as you see fit.
	 * 
	 * warning: implement a clone method if using for images of same uri.
	 */
	public class LoaderTask extends EventDispatcher implements ITask
	{
		protected var _loader:Loader;
		protected var _loadRequest:LoadRequest;
		
		/**
		 * Constructor.
		 */
		public function LoaderTask(loadRequest:LoadRequest)
		{
			_loadRequest = loadRequest;
			
			_loader = new Loader();
			_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loader_completeHandler);
			_loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, loader_errorHandler);
		}
		
		
		public function run():void
		{
			_loader.load(new URLRequest(_loadRequest.uri), new LoaderContext(false, ApplicationDomain.currentDomain));
		}
		
		public function get result():*
		{
			return _loader.content;
		}
	   
		public function get id():String
		{
			return _loadRequest.uri;
		}
		
		protected function loader_completeHandler(event:Event):void
		{
			dispatchEvent(new TaskEvent(TaskEvent.TASK_COMPLETE, _loadRequest.uri));
		}
		
		protected function loader_errorHandler(event:Event):void
		{
			dispatchEvent(new TaskEvent(TaskEvent.TASK_FAILURE, _loadRequest.uri));
		}
	}
}